package com.lq.demo.demo.netty9;

import com.lq.demo.demo.netty.protocol.*;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Date;
import java.util.Scanner;

/**
 * @Auther: LQ
 * @Date: 2018/11/23 22:40
 * @Description:
 */
public class ServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf requestByteBuf = (ByteBuf) msg;
        Packet packet = PacketCodeC.INSTANCE.decode(requestByteBuf);
        if (packet instanceof LoginRequestPacket) {
            // 登录流程
            LoginRequestPacket loginRequestPacket = (LoginRequestPacket) packet;
            LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
            loginResponsePacket.setVersion(packet.getVersion());
            if (valid(loginRequestPacket)) {
                loginResponsePacket.setSuccess(true);
                System.out.println(new Date() + ": 登录成功!");
            } else {
                loginResponsePacket.setReason("账号密码校验失败");
                loginResponsePacket.setSuccess(false);
                System.out.println(new Date() + ": 登录失败!");
            }
            ByteBuf encode = PacketCodeC.INSTANCE.encode(ctx.alloc(), loginResponsePacket);
            ctx.channel().writeAndFlush(encode);
        } else if (packet instanceof MessageRequestPacket) {
            startConsoleThread(ctx, packet);
        }

    }

    private boolean valid(LoginRequestPacket loginRequestPacket) {
        System.out.println("  校验通过" + loginRequestPacket);
        return true;
    }

    private static void startConsoleThread(ChannelHandlerContext ctx, Packet packet) {

        new Thread(() -> {
            while (!Thread.interrupted()) {
                MessageRequestPacket messageRequestPacket = (MessageRequestPacket) packet;
                String message = messageRequestPacket.getMessage();
                System.out.println(new Date() + ": 收到客户端消息: " + message);
                MessageResponsePacket messageResponsePacket = new MessageResponsePacket();
                messageResponsePacket.setVersion(packet.getVersion());
                System.out.println(" 请回复 ");
                Scanner scanner = new Scanner(System.in);
                String line = scanner.nextLine();
                messageResponsePacket.setMessage("服务端回复【" + messageRequestPacket.getMessage() + "】:" + line);
                ByteBuf responseByteBuf = PacketCodeC.INSTANCE.encode(ctx.alloc(), messageResponsePacket);
                ctx.channel().writeAndFlush(responseByteBuf);

            }
        }).start();
    }
}
